package com.self.cloudmall.oms.listener;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.google.common.collect.Maps;
import com.self.cloudmall.common.utils.R;
import com.self.cloudmall.oms.config.AlipayTemplate;
import com.self.cloudmall.oms.service.OrderService;
import com.self.cloudmall.oms.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
public class PayedNotifyListener {

    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;

    /**
     * 支付成功异步通知
     * @param payAsyncVo
     * @return
     */
    @PostMapping("/payed/notify")
    public String payNotify(PayAsyncVo payAsyncVo, HttpServletRequest  request){
        //验签
        Map<String, String> params = Maps.newHashMap();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]>  entry : parameterMap.entrySet()){
            StringBuilder builder = new StringBuilder();
            for (String val : entry.getValue()){
                builder.append(val).append(",");
            }
            params.put(entry.getKey(),builder.deleteCharAt(builder.toString().length()-1).toString());
        }
        try {
            boolean b = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                    alipayTemplate.getCharset(), alipayTemplate.getSign_type());
            if (b){
                R r= orderService.handlePayed(payAsyncVo);
                if (!r.isSuccess()){
                    //返回失败，支付宝会不断重试
                    return "error";
                }
                log.info("支付宝支付成功，回调成功");
                return "success";
            }
        } catch (AlipayApiException e) {
            log.error("支付宝验签异常：{}",e);
        }
        return "error";

    }

}
